﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace G.Net.Oauth
{

    public class Oauth2HttpPost : HttpPost
    {

        public Oauth2HttpPost(string uri)
            : base(uri)
        {
            this.Params.Add("access_token", OAuth2AccessToken.CurrentToken.AccessToken);
        }

        /// <summary>
        /// Initializes a new instance of <see cref="OAuthHttpPost"/> with the specified <paramref name="uri"/> and <paramref name="additionalParams"/>.
        /// </summary>
        /// <param name="uri">The uri to identify a resource in the remote server.</param>
        /// <param name="additionalParams">Additional data to post.</param>
        public Oauth2HttpPost(string uri, IList<ParamPair> additionalParams)
            : this(uri)
        {
            foreach (var item in additionalParams)
                this.postParams.Add(item);
        }

        private ParamCollection postParams = new ParamCollection();
        public ParamCollection Params
        {
            get
            {
                return postParams;
            }
        }


        public sealed override byte[] PostData
        {
            get
            {
                System.Text.StringBuilder sortedParamsBuilder = new System.Text.StringBuilder();
                foreach (var pair in Params)
                {
                    sortedParamsBuilder.Append(string.Format("{0}={1}&", pair.Name, HttpUtility.UrlEncode(pair.Value)));
                }
                var sortedParamsString = sortedParamsBuilder.ToString().TrimEnd('&');
                return sortedParamsString.ToString().GetBytes();
            }
            set
            {
                throw new NotSupportedException("Not supported. Please use CustomData property to convey data to post.");
            }
        }
    }
}
